﻿import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../components"

/**
 * 仪表盘页面 - 实时数据监控
 * 1. 设备选择与连接状态
 * 2. 温度/压力/流量概览卡片
 * 3. 实时趋势图
 */
Item {
    id: root

    property string currentDeviceId: ""
    property bool isConnected: false
    property var latestData: null

    property real temperatureValue: Number.NaN
    property real pressureValue: Number.NaN
    property real flowValue: Number.NaN

    Timer {
        id: refreshTimer
        interval: 1000
        running: isConnected
        repeat: true
        onTriggered: updateRealtimeData()
    }

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 20
        spacing: 12

        Component.onCompleted: {
            console.log("DashboardPage 初始化 - 设备数量:", deviceModel.count)
            if (deviceModel.count > 0) {
                deviceSelector.currentIndex = 0
                var deviceId = deviceModel.data(deviceModel.index(0, 0), 257)
                var deviceName = deviceModel.data(deviceModel.index(0, 0), 258)
                selectDevice(deviceId, deviceName)
            }
        }

        Rectangle {
            id: headerPanel
            Layout.fillWidth: true
            Layout.fillHeight: true
            Layout.preferredHeight: 1
            Layout.minimumHeight: 90
            Layout.maximumHeight: 140
            color: "white"
            radius: 12
            layer.enabled: true

            RowLayout {
                anchors.fill: parent
                anchors.margins: 24
                spacing: 24

                Column {
                    Layout.preferredWidth: Math.max(260, headerPanel.width * 0.35)
                    Layout.fillHeight: true
                    spacing: 6

                    Text {
                        text: "监控设备"
                        font.pixelSize: 12
                        color: "#999999"
                    }

                    ComboBox {
                        id: deviceSelector
                        Layout.fillWidth: true
                        height: 40
                        model: deviceModel
                        textRole: "deviceName"
                        displayText: currentText || "请选择设备..."

                        background: Rectangle {
                            color: parent.hovered ? "#f9fafb" : "white"
                            border.color: "#d1d5db"
                            border.width: 2
                            radius: 8
                        }

                        contentItem: Text {
                            leftPadding: 15
                            rightPadding: deviceSelector.indicator.width + deviceSelector.spacing
                            text: deviceSelector.displayText
                            font.pixelSize: 14
                            color: "#333333"
                            verticalAlignment: Text.AlignVCenter
                        }

                        onActivated: function(index) {
                            if (index >= 0 && deviceModel.count > 0) {
                                var deviceId = deviceModel.data(deviceModel.index(index, 0), 257)
                                var deviceName = deviceModel.data(deviceModel.index(index, 0), 258)
                                selectDevice(deviceId, deviceName)
                            }
                        }
                    }
                }

                Rectangle {
                    width: 1
                    Layout.fillHeight: true
                    color: "#e5e7eb"
                }

                RowLayout {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    spacing: 16

                    DeviceStatus {
                        id: deviceStatus
                        Layout.alignment: Qt.AlignVCenter
                        status: isConnected ? "online" : "offline"
                    }

                    Item { Layout.fillWidth: true }

                    Button {
                        visible: currentDeviceId !== ""
                        text: isConnected ? "断开连接" : "连接设备"
                        Layout.preferredHeight: 40
                        Layout.preferredWidth: 140

                        background: Rectangle {
                            color: !isConnected
                                   ? (parent.hovered ? "#2563eb" : "#3b82f6")
                                   : (parent.hovered ? "#dc2626" : "#ef4444")
                            radius: 8
                        }

                        contentItem: Text {
                            text: parent.text
                            font.pixelSize: 14
                            font.bold: true
                            color: "white"
                            horizontalAlignment: Text.AlignHCenter
                            verticalAlignment: Text.AlignVCenter
                        }

                        onClicked: isConnected ? disconnectDevice() : connectDevice()
                    }
                }
            }
        }


        StackLayout {
            Layout.fillWidth: true
            Layout.fillHeight: true
            Layout.preferredHeight: 5
            currentIndex: deviceModel.count > 0 ? 0 : 1

            ColumnLayout {
                id: dashboardContent
                spacing: 16
                Layout.fillWidth: true
                Layout.fillHeight: true

                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    Layout.preferredHeight: 2
                    Layout.minimumHeight: 170
                    color: "white"
                    radius: 12
                    layer.enabled: true

                    RowLayout {
                        anchors.fill: parent
                        anchors.margins: 20
                        spacing: 16
                        Layout.minimumHeight: 160

                        Rectangle {
                            id: temperatureSummaryCard
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            Layout.minimumWidth: 220
                            Layout.preferredHeight: 1
                            radius: 12
                            color: "#fff5f5"
                            border.color: "#fecaca"
                            border.width: 1
                            property string statusValue: getStatusForValue("temperature", temperatureValue)

                            ColumnLayout {
                                anchors.fill: parent
                                anchors.margins: 18
                                spacing: 12

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: 10
                                    Text { text: "🌡️"; font.pixelSize: 28 }
                                    ColumnLayout {
                                        Layout.fillWidth: true
                                        spacing: 2
                                        Text { text: "温度"; font.pixelSize: 13; color: "#666666" }
                                        Text { text: isConnected ? "实时监测" : "待连接"; font.pixelSize: 11; color: "#94a3b8" }
                                    }
                                    Rectangle {
                                        width: 8; height: 8; radius: 4; color: "#ef4444"
                                        opacity: isConnected ? 1 : 0.3
                                        SequentialAnimation on opacity {
                                            running: isConnected
                                            loops: Animation.Infinite
                                            NumberAnimation { from: 1.0; to: 0.3; duration: 400 }
                                            NumberAnimation { from: 0.3; to: 1.0; duration: 400 }
                                        }
                                    }
                                }

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: 6
                                    Text { text: formatValue(temperatureValue, 1); font.pixelSize: 42; font.bold: true; color: "#1f2937" }
                                    Text { text: "℃"; font.pixelSize: 16; color: "#9ca3af"; Layout.alignment: Qt.AlignBottom }
                                }

                                Rectangle {
                                    Layout.alignment: Qt.AlignLeft | Qt.AlignBottom
                                    Layout.topMargin: 8
                                    width: tempStatusText.paintedWidth + 28
                                    height: 26
                                    radius: 13
                                    color: getStatusBadgeBg(temperatureSummaryCard.statusValue)

                                    Text {
                                        id: tempStatusText
                                        anchors.centerIn: parent
                                        text: getStatusBadgeText(temperatureSummaryCard.statusValue)
                                        font.pixelSize: 12
                                        color: getStatusBadgeFg(temperatureSummaryCard.statusValue)
                                    }
                                }

                                Item { Layout.fillHeight: true }
                            }
                        }

                        Rectangle {
                            id: pressureSummaryCard
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            Layout.minimumWidth: 220
                            Layout.preferredHeight: 1
                            radius: 12
                            color: "#f5f8ff"
                            border.color: "#bfdbfe"
                            border.width: 1
                            property string statusValue: getStatusForValue("pressure", pressureValue)

                            ColumnLayout {
                                anchors.fill: parent
                                anchors.margins: 18
                                spacing: 12

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: 10
                                    Text { text: "💨"; font.pixelSize: 28 }
                                    ColumnLayout {
                                        Layout.fillWidth: true
                                        spacing: 2
                                        Text { text: "压力"; font.pixelSize: 13; color: "#666666" }
                                        Text { text: isConnected ? "实时监测" : "待连接"; font.pixelSize: 11; color: "#94a3b8" }
                                    }
                                    Rectangle {
                                        width: 8; height: 8; radius: 4; color: "#3b82f6"
                                        opacity: isConnected ? 1 : 0.3
                                        SequentialAnimation on opacity {
                                            running: isConnected
                                            loops: Animation.Infinite
                                            NumberAnimation { from: 1.0; to: 0.3; duration: 400 }
                                            NumberAnimation { from: 0.3; to: 1.0; duration: 400 }
                                        }
                                    }
                                }

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: 6
                                    Text { text: formatValue(pressureValue, 1); font.pixelSize: 42; font.bold: true; color: "#1f2937" }
                                    Text { text: "kPa"; font.pixelSize: 16; color: "#9ca3af"; Layout.alignment: Qt.AlignBottom }
                                }

                                Rectangle {
                                    Layout.alignment: Qt.AlignLeft | Qt.AlignBottom
                                    Layout.topMargin: 8
                                    width: pressureStatusText.paintedWidth + 28
                                    height: 26
                                    radius: 13
                                    color: getStatusBadgeBg(pressureSummaryCard.statusValue)

                                    Text {
                                        id: pressureStatusText
                                        anchors.centerIn: parent
                                        text: getStatusBadgeText(pressureSummaryCard.statusValue)
                                        font.pixelSize: 12
                                        color: getStatusBadgeFg(pressureSummaryCard.statusValue)
                                    }
                                }

                                Item { Layout.fillHeight: true }
                            }
                        }

                        Rectangle {
                            id: flowSummaryCard
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            Layout.minimumWidth: 220
                            Layout.preferredHeight: 1
                            radius: 12
                            color: "#f3fff8"
                            border.color: "#bbf7d0"
                            border.width: 1
                            property string statusValue: getStatusForValue("flow", flowValue)

                            ColumnLayout {
                                anchors.fill: parent
                                anchors.margins: 18
                                spacing: 12

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: 10
                                    Text { text: "💧"; font.pixelSize: 28 }
                                    ColumnLayout {
                                        Layout.fillWidth: true
                                        spacing: 2
                                        Text { text: "流量"; font.pixelSize: 13; color: "#666666" }
                                        Text { text: isConnected ? "实时监测" : "待连接"; font.pixelSize: 11; color: "#94a3b8" }
                                    }
                                    Rectangle {
                                        width: 8; height: 8; radius: 4; color: "#10b981"
                                        opacity: isConnected ? 1 : 0.3
                                        SequentialAnimation on opacity {
                                            running: isConnected
                                            loops: Animation.Infinite
                                            NumberAnimation { from: 1.0; to: 0.3; duration: 400 }
                                            NumberAnimation { from: 0.3; to: 1.0; duration: 400 }
                                        }
                                    }
                                }

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: 6
                                    Text { text: formatValue(flowValue, 2); font.pixelSize: 42; font.bold: true; color: "#1f2937" }
                                    Text { text: "L/min"; font.pixelSize: 16; color: "#9ca3af"; Layout.alignment: Qt.AlignBottom }
                                }

                                Rectangle {
                                    Layout.alignment: Qt.AlignLeft | Qt.AlignBottom
                                    Layout.topMargin: 8
                                    width: flowStatusText.paintedWidth + 28
                                    height: 26
                                    radius: 13
                                    color: getStatusBadgeBg(flowSummaryCard.statusValue)

                                    Text {
                                        id: flowStatusText
                                        anchors.centerIn: parent
                                        text: getStatusBadgeText(flowSummaryCard.statusValue)
                                        font.pixelSize: 12
                                        color: getStatusBadgeFg(flowSummaryCard.statusValue)
                                    }
                                }

                                Item { Layout.fillHeight: true }
                            }
                        }
                    }
                }

                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    Layout.preferredHeight: 360
                    Layout.minimumHeight: 300
                    color: "white"
                    radius: 12
                    layer.enabled: true

                    ColumnLayout {
                        anchors.fill: parent
                        anchors.margins: 12
                        spacing: 16

                        Text {
                            text: "📈 实时数据趋势"
                            font.pixelSize: 18
                            font.bold: true
                            color: "#333333"
                        }

                        RowLayout {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            spacing: 12

                            Rectangle {
                                Layout.fillWidth: true
                                Layout.fillHeight: true
                                Layout.minimumWidth: 220
                                color: "#fef2f2"
                                radius: 12
                                border.color: "#fecaca"
                                border.width: 1

                                RealtimeChart {
                                    id: temperatureChart
                                    anchors.fill: parent
                                    anchors.margins: 12
                                    chartType: "temperature"
                                    title: "温度趋势"
                                    lineColor: "#ef4444"
                                    maxDataPoints: 60
                                }
                            }

                            Rectangle {
                                Layout.fillWidth: true
                                Layout.fillHeight: true
                                Layout.minimumWidth: 220
                                color: "#eff6ff"
                                radius: 12
                                border.color: "#bfdbfe"
                                border.width: 1

                                RealtimeChart {
                                    id: pressureChart
                                    anchors.fill: parent
                                    anchors.margins: 12
                                    chartType: "pressure"
                                    title: "压力趋势"
                                    lineColor: "#3b82f6"
                                    maxDataPoints: 60
                                }
                            }

                            Rectangle {
                                Layout.fillWidth: true
                                Layout.fillHeight: true
                                Layout.minimumWidth: 220
                                color: "#f0fdf4"
                                radius: 12
                                border.color: "#bbf7d0"
                                border.width: 1

                                RealtimeChart {
                                    id: flowChart
                                    anchors.fill: parent
                                    anchors.margins: 12
                                    chartType: "flow"
                                    title: "流量趋势"
                                    lineColor: "#10b981"
                                    maxDataPoints: 60
                                }
                            }
                        }
                    }
                }
            }

            Rectangle {
                Layout.fillWidth: true
                Layout.fillHeight: true
                color: "white"
                radius: 12
                layer.enabled: true

                Column {
                    anchors.centerIn: parent
                    spacing: 12
                    width: parent.width * 0.5

                    Text {
                        text: "📭"
                        font.pixelSize: 64
                        anchors.horizontalCenter: parent.horizontalCenter
                    }

                    Text {
                        text: "暂无设备"
                        font.pixelSize: 20
                        font.bold: true
                        color: "#9ca3af"
                        anchors.horizontalCenter: parent.horizontalCenter
                    }

                    Text {
                        text: "请先在“设备管理”页面添加并连接设备。"
                        font.pixelSize: 14
                        color: "#9ca3af"
                        wrapMode: Text.Wrap
                        anchors.horizontalCenter: parent.horizontalCenter
                        horizontalAlignment: Text.AlignHCenter
                    }
                }
            }
        }

        }
    Connections {
        target: modbusController

        function onDeviceConnected(deviceId) {
            console.log("设备已连接", deviceId)
            if (deviceId === currentDeviceId) {
                isConnected = true
                console.log("当前设备连接成功，开始刷新数据")
                loadHistoricalData()
            }
        }

        function onDeviceDisconnected(deviceId) {
            console.log("设备已断开", deviceId)
            if (deviceId === currentDeviceId) {
                isConnected = false
                temperatureValue = Number.NaN
                pressureValue = Number.NaN
                flowValue = Number.NaN
            }
        }
    }

    Connections {
        target: dataRecordModel

        function onDataPointAdded(deviceId) {
            if (deviceId === currentDeviceId) {
                updateRealtimeData()
            }
        }
    }

    Connections {
        target: deviceModel

        function onCountChanged() {
            console.log("DeviceModel count changed:", deviceModel.count)
            if (currentDeviceId === "" && deviceModel.count > 0) {
                deviceSelector.currentIndex = 0
                var deviceId = deviceModel.data(deviceModel.index(0, 0), 257)
                var deviceName = deviceModel.data(deviceModel.index(0, 0), 258)
                selectDevice(deviceId, deviceName)
            }
        }
    }

    function selectDevice(deviceId, deviceName) {
        console.log("选择设备:", deviceId, deviceName)

        if (currentDeviceId !== "" && isConnected) {
            disconnectDevice()
        }

        currentDeviceId = deviceId

        temperatureChart.clearData()
        pressureChart.clearData()
        flowChart.clearData()
        temperatureValue = Number.NaN
        pressureValue = Number.NaN
        flowValue = Number.NaN

        dataRecordModel.currentDeviceId = deviceId
        loadHistoricalData()
    }

    function connectDevice() {
        if (currentDeviceId === "") {
            console.warn("未选择设备")
            return
        }

        console.log("连接设备:", currentDeviceId)
        if (!modbusController.connectToDevice(currentDeviceId)) {
            console.error("连接设备失败:", currentDeviceId)
        }
    }

    function disconnectDevice() {
        if (currentDeviceId === "") return
        console.log("断开设备:", currentDeviceId)
        modbusController.disconnectFromDevice(currentDeviceId)
    }

    function updateRealtimeData() {
        if (currentDeviceId === "") {
            console.log("updateRealtimeData: 未选择设备")
            return
        }

        var tempData = dataRecordModel.getTemperatureDataForDevice(currentDeviceId)
        var pressData = dataRecordModel.getPressureDataForDevice(currentDeviceId)
        var flowData = dataRecordModel.getFlowDataForDevice(currentDeviceId)

        if (tempData.length > 0) {
            var latestTemp = tempData[tempData.length - 1]
            var latestPress = pressData[pressData.length - 1]
            var latestFlow = flowData[flowData.length - 1]

            temperatureValue = latestTemp
            pressureValue = latestPress
            flowValue = latestFlow

            temperatureChart.addDataPoint(latestTemp)
            pressureChart.addDataPoint(latestPress)
            flowChart.addDataPoint(latestFlow)
        }
    }

    function loadHistoricalData() {
        if (currentDeviceId === "") return

        var tempData = dataRecordModel.getTemperatureDataForDevice(currentDeviceId)
        var pressData = dataRecordModel.getPressureDataForDevice(currentDeviceId)
        var flowData = dataRecordModel.getFlowDataForDevice(currentDeviceId)

        if (tempData.length > 0) {
            temperatureChart.updateDataSeries(tempData)
            pressureChart.updateDataSeries(pressData)
            flowChart.updateDataSeries(flowData)

            temperatureValue = tempData[tempData.length - 1]
            pressureValue = pressData[pressData.length - 1]
            flowValue = flowData[flowData.length - 1]
        } else {
            console.log("暂无历史数据")
        }
    }

    function getWarningThreshold(type) {
        if (!config) return getDefaultWarningThreshold(type)
        switch (type) {
        case "temperature": return config.tempWarningThreshold()
        case "pressure": return config.pressureWarningThreshold()
        case "flow": return config.flowWarningThreshold()
        default: return 0.0
        }
    }

    function getCriticalThreshold(type) {
        if (!config) return getDefaultCriticalThreshold(type)
        switch (type) {
        case "temperature": return config.tempCriticalThreshold()
        case "pressure": return config.pressureCriticalThreshold()
        default: return 999999
        }
    }

    function getDefaultWarningThreshold(type) {
        switch (type) {
        case "temperature": return 80.0
        case "pressure": return 500.0
        case "flow": return 100.0
        default: return 0.0
        }
    }

    function getDefaultCriticalThreshold(type) {
        switch (type) {
        case "temperature": return 100.0
        case "pressure": return 800.0
        default: return 999999
        }
    }

    function formatValue(value, precision) {
        if (value === undefined || value === null || !isFinite(value))
            return "--"
        return Number(value).toFixed(precision)
    }

    function getStatusForValue(type, value) {
        if (value === undefined || value === null || !isFinite(value))
            return "unknown"
        var warning = getWarningThreshold(type)
        var critical = getCriticalThreshold(type)
        if (value >= critical)
            return "critical"
        if (value >= warning)
            return "warning"
        return "normal"
    }

    function getStatusBadgeText(status) {
        switch (status) {
        case "critical": return "⚠ 严重"
        case "warning": return "⚠ 警告"
        case "normal": return "✔ 正常"
        default: return "等待数据"
        }
    }

    function getStatusBadgeBg(status) {
        switch (status) {
        case "critical": return "#fee2e2"
        case "warning": return "#fef3c7"
        case "normal": return "#dcfce7"
        default: return "#e5e7eb"
        }
    }

    function getStatusBadgeFg(status) {
        switch (status) {
        case "critical": return "#b91c1c"
        case "warning": return "#92400e"
        case "normal": return "#166534"
        default: return "#475569"
        }
    }
}

